package com.github.nukc.stateview.animations;

import com.github.nukc.stateview.AnimatorProvider;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentParent;

/**
 * SlideAnimatorProvider
 *
 * @since 2021-04-26
 */
public class SlideAnimatorProvider implements AnimatorProvider {

    private int halfWidthOfComponent = 0;
    private boolean isConstraint = false;
    private boolean isRelative = false;

    public boolean isConstraint() {
        return isConstraint;
    }

    public void setConstraint(boolean constraint) {
        isConstraint = constraint;
    }

    public boolean isRelative() {
        return isRelative;
    }

    public void setRelative(boolean relative) {
        isRelative = relative;
    }

    public int getHalfWidthOfComponent() {
        return halfWidthOfComponent;
    }

    public void setHalfWidthOfComponent(int halfWidthOfComponent) {
        this.halfWidthOfComponent = halfWidthOfComponent;
    }

    @Override
    public Animator showAnimation(Component view) {
        final int dividerNum = 2;
        final float targetX;
        if (isConstraint()) {
            targetX = getDistance(view) / dividerNum - getHalfWidthOfComponent();
        } else if (isRelative()) {
            final int relativeDistance = 150;
            targetX = relativeDistance;
        } else {
            targetX = 0;
        }

        AnimatorProperty animatorProperty = view.createAnimatorProperty();
        animatorProperty.setTarget(view);
        animatorProperty.alpha(1f);
        animatorProperty.moveFromX(getDistance(view));
        animatorProperty.moveToX(targetX);
        animatorProperty.setCurveType(Animator.CurveType.ACCELERATE);
        return animatorProperty;
    }

    @Override
    public Animator hideAnimation(Component view) {
        AnimatorProperty animatorProperty = view.createAnimatorProperty();
        animatorProperty.setTarget(view);
        animatorProperty.alpha(0f);
        animatorProperty.moveFromX(0);
        animatorProperty.moveToX(getDistance(view));
        animatorProperty.setCurveType(Animator.CurveType.DECELERATE);
        return animatorProperty;
    }

    private float getDistance(Component view) {
        ComponentParent viewParent = view.getComponentParent();
        if (viewParent == null) {
            return 0f;
        } else {
            return ((Component) viewParent).getWidth();
        }
    }
}
